package com.zdzh.socketio.socket.initializer;

import com.zdzh.socketio.socket.listener.ClientListener;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIONamespace;
import com.corundumstudio.socketio.SocketIOServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;

@Slf4j
@org.springframework.context.annotation.Configuration
public class SocketServerInitialization {

    @Value("${socket-io.config.port}")
    private Integer port;

    @Value("${socket-io.config.boss-threads}")
    private Integer bossThreads;

    @Value("${socket-io.config.worker-threads}")
    private Integer workerThreads;

    @Value("${socket-io.config.ping-interval}")
    private Integer pingInterval;

    @Value("${socket-io.config.ping-timeout}")
    private Integer pingTimeout;

    @Value("${socket-io.config.upgrade-timeout}")
    private Integer upgradeTimeout;
    @Value("${socket-io.config.context}")
    private String context;

    @Value("${socket-io.config.namespace}")
    private String namespace;

    @Autowired
    private SocketIOServer server;

    @PostConstruct
    public void run() {
        server.start();
    }

    @Bean
    public SocketIOServer init() {
        Configuration config = new Configuration();
        config.setPort(port);
        // 等同netty中的boss与worker
        config.setBossThreads(bossThreads);
        config.setWorkerThreads(workerThreads);
        //config.setContext(context);
        // Ping消息间隔（毫秒），默认25000。客户端向服务器发送一条心跳消息间隔
        config.setPingInterval(pingInterval);
        // Ping消息超时时间（毫秒），默认60000，这个时间间隔内没有接收到心跳消息就会发送超时事件
        config.setPingTimeout(pingTimeout);
        // 协议升级超时时间（毫秒），默认10000。HTTP握手升级为ws协议超时时间
        config.setUpgradeTimeout(upgradeTimeout);
        // 地址重用
        config.getSocketConfig().setReuseAddress(true);
        // TCP连接保持活跃
        config.getSocketConfig().setTcpKeepAlive(true);
        // 开启TCP无延迟
        config.getSocketConfig().setTcpNoDelay(true);
        // 握手协议参数使用JWT的Token认证方案
        config.setAuthorizationListener(data -> true);

        return new SocketIOServer(config);
    }

    @Bean(name = "clientNamespace")
    public SocketIONamespace clientNamespace(SocketIOServer server){
        SocketIONamespace socketIONamespace = server.addNamespace(namespace);
        socketIONamespace.addListeners(new ClientListener());
        return socketIONamespace;
    }
}
